const mongoose = require('mongoose');

// 连接字符串 - 使用环境变量或默认值
const connection = process.env.MONGODB_URI || 'mongodb+srv://2818975440:19931573138%2E%40asd@cluster0.bjslyrs.mongodb.net';

// 改进连接配置，增加超时设置
mongoose.connect(connection, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    dbName: 'order_management', // 指定数据库名称
    serverSelectionTimeoutMS: 15000, // 增加服务器选择超时时间
    connectTimeoutMS: 15000, // 增加连接超时时间
    socketTimeoutMS: 30000 // 增加套接字超时时间
})
    .then(() => {
        console.log('MongoDB 连接成功！');
    })
    .catch((err) => {
        console.log('MongoDB 连接失败:', err);
    });

// 定义模式
const registerSchema = new mongoose.Schema({
    password: String,
    email: {
        type: String,
        required: true,
        unique: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
});

const conversationSchema = new mongoose.Schema({
    title: {
      type: String,
      required: true,
      trim: true,
      maxlength: 100
    },
    model: {
      type: String,
      required: true,
      enum: ['Qwen2.5-VL-72B', 'Qwen2.5-32B', 'claude-2', 'llama-2', 'palm-2']
    },
    checkpoints: {
      type: [String],
      validate: {
        validator: function(v) {
          return v.length <= 3; // 最多选择3个检查点
        },
        message: '最多只能选择3个检查点'
      }
    },
    preferredName: {
      type: String,
      default: 'User',
      trim: true,
      maxlength: 20
    },
    icon: {
      type: String,
      default: 'default'
    },
    communicationStyle: {
      type: String,
      enum: ['casual', 'formal', 'fun'],
      default: 'formal'
    },
    therapyGoal: {
      type: String,
      default: '降低压力水平'
    },
    isPublic: {
      type: Boolean,
      default: false
    },
    createdAt: {
      type: Date,
      default: Date.now
    }
  });
  


  const counterSchema = new mongoose.Schema({
    name: { type: String, required: true, unique: true },
    count: { type: Number, default: 0 }
  });
  



// 创建模型
const registerModel = mongoose.model('registerEr', registerSchema, 'registerEr');
const Counter = mongoose.model('Counter', counterSchema);
const conversation=mongoose.model("conversationSchema",conversationSchema,"conversationSchema")

// 监听连接事件
mongoose.connection.on('error', (err) => {
    console.error('MongoDB 连接错误:', err);
});

mongoose.connection.on('disconnected', () => {
    console.log('MongoDB 连接断开，尝试重新连接...');
});

mongoose.connection.on('reconnected', () => {
    console.log('MongoDB 重新连接成功');
});

module.exports = { registerModel ,conversation,Counter};

